//This file contains the body parser middleware.
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:copilot_proxy/context.dart';
import 'package:copilot_proxy/middleware/middleware.dart';

Future<void> bodyParserMiddleware(Context context, Next next) async {
  if (!_parseMethods.contains(context.method)) return await next();
  if (_ignorePaths.contains(context.path)) return await next();
  final body = await utf8.decoder.bind(context.request).join();
  if (body.isEmpty) return await next();
  context['body'] = body;
  final header = context.headers[HttpHeaders.contentTypeHeader];
  final contentType = header?.firstOrNull?.toLowerCase();
  if (contentType?.contains('json') ?? false) {
    context['json'] = jsonDecode(body);
  }
  await next();
}

final _parseMethods = <String>{'post', 'put'};

final _ignorePaths = <String>{};

///Ignore body parser for the specified path.
///ignored paths will not parse the request body.need process request body manually.
void ignoreParseBody(String path) => _ignorePaths.add(path);
